package com.tang.common.interceptor.frequency;

import com.tang.common.constant.BusinessConstant;
import com.tang.common.exception.NoRestrictionException;
import com.tang.common.interceptor.AbstractInterceptorHandler;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 该拦截器作用是验证该访问是否需要进行接口限制
 * @author tang
 * @date 2022/1/16 12:49
 */
@Order(2)
@Component
public class EntranceInterceptor extends AbstractInterceptorHandler {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @SneakyThrows
    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response) {
        //访问url
        String uri = request.getRequestURI();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication.getPrincipal() == null) {
            //表示这个url是一个不需要登录即可访问的url
            throw new NoRestrictionException("不需要登录的接口,无需接口限制");
        }
         //是否需要进行访问控制
        if (stringRedisTemplate.opsForHash().hasKey(BusinessConstant.INTERFACE_RESTRICTION_HASH,request.getMethod() + uri)) {
            return;
        }
        throw new NoRestrictionException("不需要接口限制");
    }
}
